package v1

import (
	"github.com/gin-gonic/gin"
	"test/globals/reps"
	"test/models"
	"test/mysql/db"
	"test/service"
)

/*
redis原子操作防止库存超卖 v1版本（亲测没问题了的）
*/
func SpikeV1(c *gin.Context) {
	var mGoods models.Goods
	c.ShouldBindJSON(&mGoods)
	spike := service.NewSpike()
	v1, err := spike.QueryRedisV1(mGoods.Id)
	if err != nil {
		reps.Success(c, "请求失败:"+err.Error(), nil)
	} else {
		reps.Success(c, "请求成功，秒杀成功", v1)
	}
}

/*
redis分布式锁锁，推荐使用这个方式
*/
func SpikeV2(c *gin.Context) {
	var mGoods models.Goods
	c.ShouldBindJSON(&mGoods)
	spike := service.NewSpike()
	v2, err := spike.QueryRedisV2(mGoods.Id)
	if err != nil {
		reps.Success(c, "请求失败:"+err.Error(), nil)
	} else {
		reps.Success(c, "请求成功，秒杀成功", v2)
	}
}

/*
给redis里面预热秒杀商品数量
*/
func AddRedis(c *gin.Context) {
	var mGoods models.Goods
	c.ShouldBindJSON(&mGoods)
	spike := service.NewSpike()
	err := spike.AddRedis(mGoods.Id, int64(mGoods.Count))
	if err != nil {
		reps.Success(c, "失败："+err.Error(), nil)
	} else {
		reps.Success(c, "成功", nil)
	}
}

func TestTime(c *gin.Context) {
	var mData models.TestTime
	err := db.GetDb().Table("setting").Find(&mData).Error
	if err != nil {
		reps.Success(c, "失败："+err.Error(), nil)
	} else {
		reps.Success(c, "成功", mData)
	}
}
